<template>
  <div class="home-container">
    <el-dialog title="个人信息" :visible.sync="infoDialogVisible" width="40%" center :close-on-click-modal="false">
      <el-form :model="userInfo" class="demo-form-inline" :rules="userInfoRules">
        <el-form :inline="true" :model="userInfo" class="demo-form-inline">
          <el-form-item label="工号：" style="text-align: left;" prop="userId">
            <el-input v-model="userInfo.userId" placeholder="请输入内容" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="姓名：" style="text-align: left;" prop="userName">
            <el-input v-model="userInfo.userName" placeholder="请输入内容"></el-input>
          </el-form-item>
        </el-form>
        <el-form-item label="身份证号：" style="text-align: left; width: 60%; " prop="userIdNumber">
          <el-input v-model="userInfo.userIdNumber" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="电话：" style="text-align: left;width: 60%;" prop="userPhone">
          <el-input v-model="userInfo.userPhone" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="年龄：" style="text-align: left;width: 60%;" prop="userAge">
          <el-input v-model="userInfo.userAge" placeholder="请输入内容"></el-input>
        </el-form-item>


      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button class="confirm-submit" @click="showChangePassword">修改密码</el-button>
        <el-button class="confirm-submit" type="primary" @click="changeUserInfo">确定修改</el-button>
      </span>
    </el-dialog>
    <el-dialog title="修改密码" :visible.sync="passwordDialogVisible" width="40%" center :close-on-click-modal="false">
      <el-form :inline="true" :model="userInfo" class="demo-form-inline">
        <el-form-item label="工号：" style="text-align: left;">
          <el-input v-model="userInfo.userId" placeholder="请输入内容" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="姓名：" style="text-align: left;">
          <el-input v-model="userInfo.userName" placeholder="请输入内容" :disabled="true"></el-input>
        </el-form-item>
      </el-form>
      <el-form :model="passwordForm" ref="passwordForm" class="demo-form-inline" :rules="rules">
        <el-form-item label="原密码：" style="text-align: left; width: 60%;" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" placeholder="请输入原密码" show-password autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="新密码：" style="text-align: left; width: 60%;" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" placeholder="请输入新密码" show-password autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码：" style="text-align: left; width: 60%;" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" placeholder="请再次输入新密码" show-password
            autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button class="confirm-submit" type="primary" @click="changeUserPassword('passwordForm')">确定修改</el-button>
      </span>
    </el-dialog>

    <div class="home-navi">
      <div class="home-navi-header">
        <div class="home-navi-header-icon"></div>
        <div class="home-navi-header-text">车辆管理系统</div>
      </div>
      <el-menu default-active="2" class="el-menu-vertical-demo home-navibar" background-color="#001529"
        text-color="#a5acb3" unique-opened active-text-color="#ffd04b">

        <template v-for="group in roleBusinessData">
          <el-submenu v-if="judgeType(group)" :key="group.businessId" :index="group.businessName"
            style="text-align: left;">
            <template slot="title">
              <span style="font-size: medium;">{{ group.businessName }}</span>
            </template>
            <template v-for="groupMember in roleBusinessData">
              <el-menu-item v-if="groupMember.fatherBusinessId == group.businessId"
                style="min-width: 0px;text-align: left;" :key="groupMember.businessId" :index="groupMember.businessName">
                <template slot="title">
                  <router-link :to="groupMember.businessRouter"><span style="display: block;width: 100%;">{{
                    groupMember.businessName
                  }}</span></router-link>
                </template>
              </el-menu-item>
            </template>
          </el-submenu>

          <el-menu-item v-if="group.fatherBusinessId == 0 && !judgeType(group)" style="text-align: left;"
            :key="group.businessId" :index="group.businessName">
            <template slot="title">
              <router-link :to="group.businessRouter"><span style="font-size: medium;display: block;width: 100%;">{{
                group.businessName
              }}</span></router-link>
            </template>
          </el-menu-item>
        </template>

      </el-menu>

      <div class="home-navi-header-footer"></div>
    </div>
    <div class="home-content">
      <div class="home-content-top">
        <div class="home-content-top-left">
          <span style="margin-left: 40px;">当前角色：{{ currentRole }}</span>
          <el-dropdown trigger="click" style="margin-left: 15px;">
            <span class="el-dropdown-link">
              切换<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <div @click="switchRole(item.userRole)" v-for="item in userRoles" :key="item.userRole"
                class="dropdown-item">{{ item.userRole }}</div>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
        <div class="home-content-top-right">
          <div class="home-content-top-icon" style="margin-right: 10px;">
          </div>
          <el-dropdown trigger="click" style="margin-right: 10px;">
            <span class="el-dropdown-link">
              {{ currentUser }}<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <div class="dropdown-item" @click="showUserInfo()">个人信息</div>
              <div class="dropdown-item" @click="Logout()">退出登录</div>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
      <div style="width: 100%;height: 90%;">
        <router-view></router-view>
      </div>
    </div>
  </div>
</template>

<style scoped>
.home-container {
  width: 100%;
  height: 100%;
  display: flex;
  position: relative;
}

.home-navi {
  width: 20%;
  /* background-color: aliceblue; */
  background-color: #001529;
  height: 100%;
  position: fixed;
}

.home-navibar {
  height: 92%;
  width: 100%;
}

.home-navibar a {
  color: #a5acb3;

  &.router-link-active {
    /* border-bottom: 4px #409eff solid; */
    /* background-color: #409eff; */
    color: #ffd04b;
  }
}

.home-navibar a:hover {
  color: #a5acb3;
}

.home-navi-header {
  width: 100%;
  height: 8%;
  /* background-color: #004585; */
  display: flex;
  justify-content: left;
  align-items: center;
}

.home-navi-header-footer {
  height: 8%;
  position: fixed;
  bottom: 15px;
  /* background-color: #fff; */
  width: 100%;
  background: url(../assets/logo无背景灰.png) no-repeat;
  background-size: contain;
}

.home-navi-header-text {
  color: #DCDFE6;
  text-align: left;
  font-size: x-large;
  /* font-weight: 500; */
}

.home-navi-header-icon {
  background: url(../assets/icon.png) no-repeat;
  background-size: contain;
  height: 80%;
  width: 20%;
  background-position: left;
  margin: 3px 10px 0 20px;
}

.home-content {
  width: 80%;
  /* background-color: #fff; */
  position: relative;
  left: 20%;
}

.home-content-top {
  width: 100%;
  height: 8%;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.home-content-top-left {
  display: flex;
  justify-content: center;
  align-items: center;
}

.home-content-top-right {
  display: flex;
  justify-content: center;
  align-items: center;
}

.home-content-top-icon {
  background: url(../assets/user.png) no-repeat;
  height: 30px;
  width: 30px;
  background-size: contain;
}

.dropdown-item {
  background-color: white;
  width: 90px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  font-size: small;
}

.dropdown-item:hover {
  background-color: #409eff;
  color: white;
  cursor: pointer;
}
</style>


<script>
import { getRoleBusiness } from "@/api/user";
import { getUserInfoById } from "@/api/user";
import { userUpdateInformation } from "@/api/user";
import { userUpdatePassword } from "@/api/user";
import CryptoJS from 'crypto-js/crypto-js.js';

export default {
  name: 'HomeView',
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      }
      else {
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      userRoles: null,
      roleBusinessData: [],
      currentUser: null,
      currentRole: null,
      userInfo: {
        userName: null,
        userId: null,
        userIdNumber: null,
        userAge: null,
        userPhone: null,
      },
      passwordForm: {
        oldPassword: null,
        newPassword: null,
        confirmPassword: null,
      },
      infoDialogVisible: false,
      passwordDialogVisible: false,
      userInfoRules: {
        userId: [
          { required: true, message: '请输入工号', trigger: 'blur' },
          { min: 8, max: 8, message: '长度为8个字符', trigger: 'blur' }
        ],
        userName: [{ required: true, message: '请输入姓名', trigger: 'blur' },],
        userIdNumber: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { min: 18, max: 18, message: '请输入正确的18位身份证号', trigger: 'blur' }
        ],
        userPhone: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { min: 11, max: 11, message: '请输入正确的11位手机号', trigger: 'blur' }
        ],
        userAge: [{ required: true, message: '请输入年龄', trigger: 'blur' },],
      },
      rules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, validator: validatePass, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, validator: validatePass2, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    judgeType(Object) {
      for (let item of this.roleBusinessData) {
        if (item.fatherBusinessId == Object.businessId) {
          return true
        }
      }
      return false;
    },
    Logout() {
      this.$confirm('此操作将退出登录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '退出成功!'
        });
        localStorage.clear();
        this.$router.replace('/');
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    switchRole(userRole) {
      this.currentRole = userRole;
      localStorage.setItem('currentRole', this.currentRole)
      getRoleBusiness(this.currentRole).then(res => {
        this.roleBusinessData = res.data.data;
      })
      this.$router.replace('/Home');
    },
    //显示修改个人信息弹窗
    showUserInfo() {
      this.infoDialogVisible = true;
      getUserInfoById(localStorage.getItem('userId')).then(res => {
        let temp = res.data.data[0]
        this.userInfo = temp;
      })
    },
    //修改个人信息
    changeUserInfo() {
      this.$confirm('此操作将修改个人信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userUpdateInformation(this.userInfo).then(res => {
          if (res.data.code === '0') {
            this.$message({
              message: res.data.msg,
              duration: 2000,
              showClose: true,
              type: 'success'
            });
            setTimeout(() => {
              location.reload()
            }, 1000)
          }
          else {
            this.$message.error(res.data.msg);
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    //显示密码修改弹窗
    showChangePassword() {
      this.passwordDialogVisible = true
    },
    //修改密码
    changeUserPassword(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm('此操作将修改个人信息, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            userUpdatePassword(this.userInfo.userId, this.encrypt(this.passwordForm.oldPassword), this.encrypt(this.passwordForm.newPassword))
              .then(res => {
                if (res.data.code === '0') {
                  this.$message({
                    message: res.data.msg,
                    duration: 2000,
                    showClose: true,
                    type: 'success'
                  });
                  setTimeout(() => {
                    location.reload();
                  }, 1000)
                }
                else {
                  this.$message.error(res.data.msg);
                }
              })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            });
          });
        } else {
          return false;
        }
      });
    },
    encrypt(plaintText) {
      const CRYPTOJSKEY = "keyhlddz";
      var plaintText1 = plaintText;
      var options = {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
      };
      var key = CryptoJS.enc.Utf8.parse(CRYPTOJSKEY);
      var encryptedData = CryptoJS.AES.encrypt(plaintText1, key, options);
      var encryptedBase64Str = encryptedData.toString().replace(/\//g, "_");
      encryptedBase64Str = encryptedBase64Str.replace(/\+/g, "-");
      return encryptedBase64Str;
    },

  },
  mounted() {
    this.currentUser = localStorage.getItem('userName');
    this.userRoles = JSON.parse(localStorage.getItem('userRoles'));
    this.currentRole = localStorage.getItem('currentRole');
    getRoleBusiness(localStorage.getItem('currentRole')).then(res => {
      this.roleBusinessData = res.data.data;
    })
  }
}
</script>